﻿using System.IO;

namespace Neoit.Utils
{
    /// <summary>
    /// FileHelper
    /// </summary>
    public static class FileHelper
    {
        /// <summary>
        /// 将Stream流转储成文件
        /// </summary>
        /// <param name="ms"></param>
        /// <param name="filename"></param>
        public static void SaveFile(this Stream ms, string filename)
        {
            using var fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
            byte[] buffer = ms.ToArray(); // 转化为byte格式存储
            fs.Write(buffer, 0, buffer.Length);
            fs.Flush();
        }
        public static byte[] ToArray(this Stream stream)
        {
            stream.Position = 0;
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);

            // 设置当前流的位置为流的开始
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }
        /// <summary>
        /// CopyStream
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="destPath"></param>
        public static void CopyStream(Stream stream, string destPath)
        {
            using var fileStream = new FileStream(destPath, FileMode.Create, FileAccess.Write);
            stream.CopyTo(fileStream);
        }

    }
}
